<template>
  <TableView
    ref="tableView"
    :toolbar-attrs="{ buttons: ['slot'] }"
    :search-model="searchForm"
    :table-attrs="{ api: fetchList, descs: ['create_time'] }">
    <template #toolbar-button>
      <UploadButton btn-style="button">
        <template #button>
          <ToolbarButton privilege="sys_file_del" icon="el-icon-upload" type="primary" label="上传" />
        </template>
      </UploadButton>
    </template>
    <template #columns>
      <TableColumn prop="bucketName" align="center" label="存储桶" />
      <TableColumn prop="fileName" label="文件名" />
      <TableColumn prop="original" label="原文件名" />
      <TableColumn prop="type" label="文件类型" />
      <TableColumn prop="fileSize" label="文件大小">
        <template #default="{ row }">
          {{ filterType(row.fileSize) }}
        </template>
      </TableColumn>
      <TableColumn prop="createBy" label="上传人" />
      <TableColumn prop="createTime" align="center" label="上传时间" />
      <TableColumn label="操作" align="center">
        <template #default="{ row }">
          <ElButton icon="el-icon-view" size="small" type="text" @click="view(row)">查看</ElButton>
          <ConfirmButton icon="el-icon-delete" size="small" type="text" @click="rowDel(row)">删除</ConfirmButton>
          <ElButton icon="el-icon-download" size="small" type="text" @click="download(row)">下载</ElButton>
        </template>
      </TableColumn>
    </template>
    <template #search-form>
      <FormInput v-model="searchForm.original" label="原文件名" prop="original" />
    </template>
  </TableView>
</template>

<script>
  import { delObj, fetchList } from '@/api/admin/sys-file'
  import { tableOption } from '@/const/crud/admin/sys-file'
  import DialogForm from '@web-utils/component/dialog-form'

  export default {
    name: 'SysFile',
    data() {
      return {
        searchForm: {
          original: ''
        }
      }
    },
    methods: {
      fetchList,
      async rowDel(row) {
        await delObj(row.id)
        this.$refs.tableView.reloadTable()
        this.$message.success('删除成功')
      },
      view(row) {
        DialogForm.showForm({
          title: row.original,
          width: '960px',
          disabled: true,
          menuPosition: 'right',
          data: row,
          option: tableOption
        })
      },
      download(row) {
        this.$downBlobFile(`/admin/sys-file/${row.bucketName}/${row.fileName}?ts=${Date.now()}`, null, row.fileName)
      },
      uploadAfter(res, done, loading) {
        if (!this.$isBlank(res.fileName)) {
          this.$message.success('上传成功')
        }
        done()
      },
      filterType(val) {
        if (!val) {
          return '-'
        }
        const k = 1024
        const sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB']
        const i = Math.floor(Math.log(val) / Math.log(k))
        return `${(val / Math.pow(k, i)).toPrecision(3)}${sizes[i]}`
      }
    }
  }
</script>
